import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-03-05
 * Time: 22:09
 */
public class JDBCInsert {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //JDBC 步骤
        //1. 创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();//向上转型
        //dataSource.setURL();//直接调用
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");//向下转型
        ((MysqlDataSource)dataSource).setUser("root");//客户端默认都是root
        ((MysqlDataSource)dataSource).setPassword("123456");//自己数据库的密码
        //2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection();//import java.sql.Connection;
        //3. 从控制台读取用户输入的数据
        System.out.println("请输入学生姓名");
        String name = scanner.nextLine();
        System.out.println("请输入学生id");
        int id = scanner.nextInt();
        //4. 构造sql语句
        //String sql = "insert student value(1, '张三')";//直接写死
        //控制台输入
        //String sql = "insert student value("+ id +", '"+ name +"')";//字符串拼接
        String sql = "insert student value(?, ?)";//使用占位符
        System.out.println(sql);
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);//用id替换第一个占位符
        statement.setString(2, name);
        //5. 执行sql语句
        int ret = statement.executeUpdate();
        System.out.println(ret);
        //6. 释放必要资源，释放顺序和创建相反
        statement.close();
        connection.close();

    }
}
